﻿using System;
using System.Collections.Generic;
using System.Linq;
using Gumini.JulaDB.Data;
using Gumini.JulaDB.Engine;
using Gumini.JulaDB.Interfaces;

namespace Gumini.JulaDB.Planner
{
    /// <summary>
    /// Represents a leaf of the query plan tree, i.e. a table. Has no child nodes.
    /// Might have a table alias.
    /// </summary>
    internal class TableNode : PlanNode
    {
        private readonly Table _table;
        private readonly string _alias;

        /// <summary>
        /// Initializes a new instance of the <see cref="TableNode"/> class.
        /// </summary>
        /// <param name="table">The source table.</param>
        /// <param name="alias">The alias (null if not specified).</param>
        public TableNode(Table table, string alias)
        {
            _table = table;
            _alias = alias;

            this.TableNames = new List<string> { _table.Definition.Name };
            if (_alias != null)
                this.TableNames.Add(_alias);
        }

        public override List<Row> Execute()
        {
            return _table.Rows;
        }

        /// <summary>
        /// A colllection of table names (1 or 2). Table can have 2 names if there is an alias defined.
        /// </summary>
        public List<string> TableNames { get; private set; }
        
        public override IHeading<TemporaryColumn> GetColumns()
        {
            return new TableHeading<TemporaryColumn>(
                _table.Definition.Heading.Select(c => new TemporaryColumn(c.Type, c.ColumnName, this.TableNames)));
        }

        protected override string GetNodeDescription()
        {
            return String.Format("TABLE ({0})", _table.Definition.Name);
        }
    }
}
